// user api
const Service = require('egg').Service;
const object = require("./get/object.js");
const time = require("./get/time.js");

class UserService extends Service {
    //注册
    async regist(tel, psd) {
        let code = 1, msg = "注册成功！"
        let end = await this.app.mysql.get("user", { tel });
        if (end) {
            code = 2;
            msg = "该账号已注册！";
        } else {
            end = await this.app.mysql.insert("user", { tel, psd, nickname: "user_" + tel });
            if (end.affectedRows == 0) {
                code = 0;
                msg = "注册失败！";
            }
        }
        return { code, msg };
    }
    //登录
    //type: psd（密码登录） sms（短信登录）
    async login(type = "psd", tel, psd, captcha) {
        let { ctx, app, service } = this;
        let code = 1, msg = "登录成功！", data = null, isAllMatch = true;
        let end = await this.app.mysql.get("user", { tel });
        if (!end) {
            code = 2;
            msg = "该账号不存在！";
        } else {
            if (type === "psd") {
                if (end.psd !== psd) {
                    code = 3;
                    msg = "密码错误！";
                    isAllMatch = false;
                } else if (captcha.toUpperCase() !== ctx.session.captcha.toUpperCase()) {
                    code = 4;
                    msg = "验证码错误！";
                    isAllMatch = false;
                }
            } else if (type === "sms") {
                code = 5;
                msg = "暂未开通短信登录功能！";
                isAllMatch = false;
            }else if(type==="auto"){
                
            }
            if (isAllMatch) {
                delete end.psd;
                let dealsTotal = await service.goods.dealsTotal(tel);
                end.avatar =`${app.baseUrl}/public/img/avatar/${end.avatar}`;
                let token = app.jwt.sign({ tel, psd }, app.config.jwt.secret, {
                    expiresIn: '1800s',
                });
                ctx.cookies.set('token', token, {
                    maxAge: 1000 * 3600 * 24, // cookie存储一天 设置过期时间后关闭浏览器重新打开cookie还存在
                    httpOnly: false, // 仅允许服务获取,不允许js获取
                    signed: true, // 对cookie进行签名 防止用户修改cookie
                    encrypt: false // 是否对cookie进行加密 如果cookie加密那么获取的时候要对cookie进行解密
                });
                data = { ...end, ...dealsTotal };
            }
        }
        return { code, msg, data }
    }
    //退出
    async out(id) {
        //退出登录转态
        //修改最后一次登录时间
        this.ctx.cookies.set('token', null);
        let sql = `update user set lastTime='${time.now()}' where id=${id}`;
        let end = this.app.mysql.query(sql);
        return end;
    }
    //获取优惠券信息
    async getVoucher(userId) {
        let sql = `SELECT vl.id,useCase,startTime,endTime,faceVal,theme FROM voucher_log vl INNER JOIN voucher v ON vl.voucherId=v.id WHERE userId=${userId} ORDER BY getTime DESC;`;
        let end = await this.app.mysql.query(sql);
        return end;
    }
    //修改头像
    async updateAvatar() {

    }
    //修改资料
    async updateInfo(userId, nickname, psd, name, sex, birthday) {
        let setStr = object.toSqlSetStr({ nickname, psd, name, sex, birthday });
        let sql = `UPDATE user SET ${setStr} WHERE id = ${userId} `;
        let end = await this.app.mysql.query(sql);
        return end;
    }
}

module.exports = UserService;